package it.uni.bo.monitoring.protocol.unmarshaller.analysis;

import it.uni.bo.monitoring.mapping.hibernate.Sla;
import it.uni.bo.monitoring.protocol.unmarshaller.EventInfo;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import static it.uni.bo.monitoring.service.StaticFields.QUERY_INTER;
import static it.uni.bo.monitoring.service.StaticFields.QUERY_SLA3;

public class StateControl implements Validation {
	
	private Session session;
	private SessionFactory factory;
	private Logger l;
	
	private static final String ERROR_SLA="sla non trovato o non attivo";
	private static final String ERROR_INTER="utente non attivo";
	
	public StateControl(SessionFactory factory) {
		l = Logger.getLogger(this.getClass());
		this.factory=factory;
	}

	public boolean validate(EventInfo ei) {
		boolean ok=true;
		session = factory.openSession();
		ok=		slaControl(ei) 	&&
		interlocutorControl(ei);
		if(session!=null){
			if (session.isOpen()) 
				session.close(); }

		//l.info("StateControl: "+ok);
		return ok;
	}
	
	private boolean slaControl(EventInfo ei) {
		Query query = session.createQuery(QUERY_SLA3);
		query.setLong(0, ei.getIdA());
		query.setLong(1, ei.getIdU());
		query.setCharacter(2, '0');
		l.info("Hibernate: "+QUERY_SLA3+" --[ "+ei.getIdA()+" "+ei.getIdU()+" '0' ]");
		query.setMaxResults(1);
		Object ob = query.uniqueResult();
		if(ob!=null){
			if(ob instanceof Sla){
				Sla sla = (Sla)ob;
				ei.setIdSla(sla.getIdSla());
				return true;
			}
		}
		l.error(ERROR_SLA);
		return false;
	}
	
	private boolean interlocutorControl(EventInfo ei){
		Query query = session.createQuery(QUERY_INTER);
		query.setLong(0, ei.getIdU());
		query.setCharacter(1, '0');
		//l.info("Hibernate: "+QUERY_INTER+" --[ "+ei.getIdU()+" '0' ]");
		query.setMaxResults(1);
		long num = (Long) query.uniqueResult();

		if(num>0){
			return true;
		}
		l.error(ERROR_INTER);
		return false;
	}

}
